package com.alinesno.cloud.portal.auto.tool.maven;

import java.io.File;
import java.io.IOException;

import org.apache.commons.io.FileUtils;
import org.apache.commons.lang.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.util.ResourceUtils;

import com.alinesno.cloud.portal.auto.constants.CommonPath;
import com.alinesno.cloud.portal.auto.tool.cmd.domain.CmdResult;
import com.alinesno.cloud.portal.auto.tool.cmd.runner.CmdExecutor;
import com.alinesno.cloud.portal.auto.tool.cmd.runner.Log;
import com.alinesno.cloud.portal.auto.tool.cmd.runner.LogListener;
import com.google.common.base.Charsets;
import com.google.common.collect.Lists;

/**
 * 创建maven工程 , 然后动态生成java类，复制到maven工程中，同时运行单元测试或者压力测试
 * @author WeiXiaoJin
 * @since 2019年11月21日 上午8:41:14
 */
public class MvnProjectBuilder {

	private static final Logger log = LoggerFactory.getLogger(MvnProjectBuilder.class) ; 
	
	/**
	 * 通过命令行生成maven工程 , 目录按(jobName/version)
	 * @param createDir 生成的目录
	 * @param jobName 任务名称
	 * @param scalaCode 运行脚本 
	 * @param packageName 包名称
	 * @return 生成的项目路径
	 * @throws IOException 
	 */
	public String createGatlingMavenJob(String createDir , String version ,  String jobName , String mvnHome, String scalaCode) throws IOException {
		log.debug("create dir :{} , job name:{} , version:{}" , createDir , jobName  , version);

	    String path = null ; 
		if(StringUtils.isBlank(createDir)) {
	        path = CommonPath.autoHome()+ File.separator + jobName ;
		}
		
		// 1. 创建目录
		String jobParentPath = path + File.separator + version ; 
		File jobParentFile = new File(jobParentPath) ; 
		if(!jobParentFile.exists()) {
			jobParentFile.mkdirs() ; 
		}
		
		// 2. 复制seed 
		File seed = ResourceUtils.getFile("classpath:seed/gatling-seed");
		FileUtils.copyDirectory(seed, jobParentFile);
		
		// 2. 复制脚本
		scalaCode = scalaCode.replaceAll("\\|", "\r\n") ; 
		log.debug("scala code:{}" , scalaCode);
		FileUtils.writeStringToFile(new File(CommonPath.scalaFilePath(jobParentPath)), scalaCode, Charsets.UTF_8.name(), false); 
		
		// 3. 更新工程路径
		String jobPath = jobParentFile.getAbsolutePath() ; // + File.separator + seed.getName() ; 
		log.debug("jobPath:{}" , jobPath);
		
		// 4. 执行压力测试任务
		buildMvn(jobPath , mvnHome) ; 
		
		// 5. 获取生成的报告路径
		return createDir + jobName ; 
	}
	
	private void buildMvn(String mvnJobPath , String mvnHome) throws IOException {
		
		ClassLoader loader = this.getClass().getClassLoader();
        String path = loader.getResource("shell"+File.separator+"maven.sh").getFile();
        
        Runtime.getRuntime().exec("chmod +x " + path);
        
        String mvnCmd = path + " "+mvnJobPath + " " + mvnHome + " > "+mvnJobPath+"/run.log" ; 
        log.debug("mvn Cmd:{}" , mvnCmd);

        CmdExecutor executor = new CmdExecutor(null,
            logListener,
            null,
            null,
            Lists.newArrayList("CMD_RUNNER_TEST"),
            null,
            Lists.newArrayList(String.format("source %s", mvnCmd)));
        CmdResult result = executor.run();
        
        log.debug("result = {}" , result);
	}
	
	private LogListener logListener = new LogListener() {
        @Override
        public void onLog(Log log) {
            System.out.println(log);
        }

        @Override
        public void onFinish() {

        }
    };
	
}
